import setting
import pymysql

def Getconnection():
    conn = pymysql.connect(
        port=setting.MYSQL_PORT,
        host=setting.MYSQL_HOST,  # 数据库地址
        user=setting.MYSQL_USER,  # 数据库用户
        password=setting.MYSQL_PASSWORD,  # 数据库密码
        database=setting.MYSQL_DB, #数据库名称
        charset="utf8",  # 数据库字符格式
    )
    return conn


class Mysql():
    def __init__(self):
        self.conn = Getconnection()
        self.cursor=self.conn.cursor()

    def shop_insert(self,values):
        sql = ""
        t = ""
        for j in values:
            t += "("+str(j[0])
            for i in j[1:]:
                t+= ","+str(i)
            t+='),'
        t = t[:-1]
        sql = f"insert into shop values{t}"
        print(sql)

        try:
            # 执行sql语句
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.conn.commit()
            print('插入完毕')
        except:
            # 如果发生错误则回滚
            print('插入错误,进行回滚')
            self.conn.rollback()


    def close(self):
        self.cursor.close()  # 关闭游标
        self.conn.close()     # 关闭数据库连接


# cursors = conn.cursor()  # 获取游标
# sql="SELECT VERSION()"
# cursors.execute(sql)
# data = cursors.fetchone()  # 获取单条返回数据
# print(data)
#
# cursors.close()  # 关闭游标
# conn.close()  # 关闭数据库连接

